interface ResponseData<T = any> {
  data: T;
  errCode: number;
  errMsg: string;
}

type ReplaceProperty<T, K extends keyof T, NewType> = Omit<T, K> & {
  [P in K]: NewType;
};

export type Config<T = any> = Omit<
  UniNamespace.RequestOptions,
  "success" | "fail" | "url"
> & { catch?: (err: any) => ResponseData<T> & { [k: string]: any } };

export const request = <T = any>(url: string, config: Config<T> = {}) => {
  return new Promise<ResponseData<T> & { [k: string]: any }>(
    (resolve, reject) => {
      uni.request({
        ...config,
        url: `${getBaseURL()}${url}`,
        // @ts-ignore
        success(
          res: ReplaceProperty<
            UniApp.RequestSuccessCallbackResult,
            "data",
            ResponseData<T>
          >
        ) {
          // console.log("request", res);
          if (res.data.errCode === 0) {
            resolve(res.data);
          } else if (res.data.errCode === 400) {
            uni.showModal({
              title: "发生了一点意外",
              content: res.data.errMsg,
              showCancel: false,
            });
            reject(res.data);
          } else {
            if (config.catch) {
              try {
                const catchRes = config.catch?.(res.data);
                resolve(catchRes);
              } catch (error) {
                reject(res.data);
              }
              return;
            }
            uni.showToast({
              title: res.data.errMsg,
              icon: "none",
            });
            reject(res.data);
          }
        },
        fail(err) {
          if (config.catch) {
            try {
              const catchRes = config.catch?.(err);
              resolve(catchRes);
            } catch (error) {
              reject(err);
            }
          }
          reject(err);
        },
      });
    }
  );
};

export const getBaseURL = () => {
  // #ifdef H5
  if (uni.getSystemInfoSync().uniPlatform === "web") {
    return "/api/bizhi";
  }
  // #endif
  return "https://tea.qingnian8.com/api/bizhi";
};
